﻿// owner 蒋家伟

#include "IApplication.h"

// std
#include <fstream>

// qt
#include <QFile>
#include <QScreen>

#include "Application.h"
#include "StringUtils.h"

using namespace jsdk;

IApplication* jsdk::IApplication::s_pApplication = nullptr;

IApplication* jsdk::IApplication::create(int & argc, char ** argv)
{
    if (s_pApplication)
        return s_pApplication;

    return Application::create(argc, argv);
}

IApplication * jsdk::IApplication::get()
{
    return s_pApplication;
}

bool jsdk::IApplication::isRunning()
{
    return Application::isRunning();
}

const ApplicationStatus & jsdk::IApplication::getApplicationStatus()
{
    return Application::getApplicationStatus();
}

const std::wstring & jsdk::IApplication::applicationDirPath()
{
    static std::wstring s_dir = QCoreApplication::applicationDirPath().toStdWString();
    return s_dir;
}

bool jsdk::IApplication::restart()
{
#ifdef _WINDOWS
    std::wstring restartbat = IApplication::applicationDirPath() + L'/' + L"restart.bat";
    if (!QFile::exists(QString::fromStdWString(restartbat)))
    {
        std::ofstream os(restartbat, std::ios::out);
        if (os.is_open())
        {

            std::string str = "cd /d %~dp0";
            str += "\nstart ";
            str += QCoreApplication::applicationName().toStdString();
            os << str;
            os.close();
        }
        else
        {
            return false;
        }
    }
    system(StringUtils::toString(restartbat).c_str());
    IApplication::get()->exit();
#else
#error 其他系统暂未实现重启
#endif
    return true;
}

bool jsdk::IApplication::getScreenGeometry(int index, uint16_t& width, uint16_t& hegiht)
{
    QList<QScreen *> screenList = QGuiApplication::screens();
    if (index >= screenList.size())
    {
        return false;
    }

    QScreen * pScreen = screenList.value(index);
    if (!pScreen)
    {
        return false;
    }

    QRect rect = pScreen->geometry();
    width = rect.width();
    hegiht = rect.height();
    return true;
}
